import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { NewAccountHome } from '../../../components/common/newAccountHome';
import { ProgressModal } from '../../../components/common/ProgressModal';

const scale = GLOBAL.SCALE;

export class inventoryApprovalList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '盘点审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			companyIndex: 0,
			// showTimeModal: false, // 时间选择
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			saleCount: 0,
			purchaseCount: 0,
			refuseModalVisible: false,
			alertShow: false,
			options: [],
			choice: {
				corpId: 'HX02',
			},
			tabIndex:1,
			lightBoxData: {
        modalVisible: false,
        onClosePress: this._closeLightBox,
        title: '',
        rowDataList: [],
        status: 'data',
        refreshIcon: false,
      },
		}
		this.TAB_LIST = [
			{
				name: '报损报溢',
				id: '1', // TODO
				cnt:Number
			},
			 {
				name: '季度盘点',
				id: '2', // TODO
				cnt:Number
			},
			// {
			// 	name: '损溢申报',
			// 	id: '3', // TODO
			// 	cnt:Number
			// }
		]
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数
		this.taskId = '';
		this.pageParams = { // TODO
			corpId: 'HX02',
			pageNo: 1,
			pageSize: 10,
		}
	}

	async componentWillMount() {
		await this.initPage();
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let options = await HTTP.POST(API_GENERATE(API.CHECK_AUDIT_COUNT));//多帐套数量接口
		options = options || [];
		options.map(item =>{
			item.rowCount = item.totalCnt
		})
		let { corpId } = options[this.state.companyIndex] || {};
		this.TAB_LIST[0].cnt = options[this.state.companyIndex].reportedOverflowCnt
		this.TAB_LIST[1].cnt = options[this.state.companyIndex].quarterCheckCnt
		// this.TAB_LIST[2].cnt = options[this.state.companyIndex].decreaseOverflowCnt
		this.pageParams.corpId = corpId || '';
		this.pageParams.checkType = this.state.tabIndex
		let res = await HTTP.POST(API_GENERATE(API.CHECK_AUDIT_LIST), this.pageParams); // TODO
		console.log(res)
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				options,
				choice: options[this.state.companyIndex] || {}
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 刷新页面
	reloadPage= () =>{
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	// tab切换
	changeTab = (item) => {
		this.setState({
			tabIndex:item.id
		},()=>{
			this.reloadPage();
		})
	}

	// 查看审批流
  _getCheckApprove = async (item) => {
    const { choice } = this.state;
    const { corpId } = choice || {};
    // this.setState({ status: 'loading' })
		//查询审批节点
		let responseData1
		if(this.state.tabIndex!=2){
			responseData1 = await  HTTP.POST(API_GENERATE(API.CHECK_AUDIT_LOG),{
				checkType:this.state.tabIndex,
				reportId:item.reportId,
				bizObjType:'WMS_CHECK',
				processInstanceId:item.processInstanceId,
				corpId:corpId,
			});
		}
		if(this.state.tabIndex==2){
			responseData1 = await  HTTP.POST(API_GENERATE(API.CHECK_AUDIT_LOG),{
				checkType:this.state.tabIndex,
				reportId:item.reportId,
			});
		}
    responseData1 = responseData1 && responseData1.map((item) => {
      if (item.auditResult == 9) {
        item.auditResultName = '操作';
      }
      return item;
    })
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = true;
    lightBoxData.title = '审批状态';
    lightBoxData.rowDataList = responseData1;
    this.setState({
      lightBoxData,
      status: 'data'
    })
  }
  _closeLightBox = () => {
    let { lightBoxData } = this.state;
    lightBoxData.modalVisible = false;
    this.setState({ lightBoxData });
	}
	
	async _audit() {
		const { choice } = this.state;
		const { corpId } = choice || {};
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const responseData = await HTTP.POST(API_GENERATE(API.CHECK_AUDIT_STOCK), {
			checkType:this.pageParams.checkType,
			auditResult: this.isAgreed,
			auditRemark: this.remark, // 填写
			taskId:this.taskId,
			status:this.status,
			reportId:this.reportId,

		});
		this.setState({ loaded: false });
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this.initPage();
			})
		} else {
			this.requesting = false;
		}
	}

	_pass() {
		this.isAgreed = 1;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse() {
		this.isAgreed = 0;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	// tab
	_renderTabWrap() {
		const { saleCount, purchaseCount,tabIndex } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					this.TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={[styles.tabItem, tabIndex == item.id ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
								<Text style={[styles.tabText, tabIndex == item.id ? { color: '#fff' } : { color: style.color.themeColor }]}>{item.name}</Text>
								{item.cnt>0?
									<View style={[styles.numPoint, tabIndex == item.id ? { backgroundColor: '#fff' } : { backgroundColor: 'red' }]}></View> : null
								}
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	// 列表
	_renderListItem = (data) => {
		const { tabIndex } = this.state
		const { checkBeginTime, createTime, warehouseName,createName,reportId,checkSubject,taskId,processInstanceId,taskName,status,applyPersonName,checkEndTime } = data.item;
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('inventoryApprovalDetail', {
					reportId,
					taskId,
					status,
					checkType:tabIndex,
					corpId:this.state.choice.corpId,
					processInstanceId,
					callback: () => this.reloadPage()
				})
			}} style={{ marginBottom: 18 * scale }}>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
					<Text style={styles.titleText}>{reportId || '-'}</Text>
				</View>
				<View style={{ backgroundColor: '#fff', borderRadius: 4 * scale }}>
					<View style={styles.billNumWrap}>
						<View style={styles.billNumWrapTop}>
							<Text style={styles.commonTitleTop}>{checkSubject || '-'}</Text>
							<Text style={styles.commonTopRight}>{taskName?taskName:null}</Text>
						</View>
						<Text style={{fontSize:12*scale}}>仓库：{warehouseName || '-'}</Text>
					</View>
					{this.state.tabIndex==1?
					<View style={styles.billInfoWrap}>
						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={styles.commonTitle}>盘点时间</Text>
							<Text style={styles.commonTitle}>创建人</Text>
							<Text style={styles.commonTitle}>提交时间</Text>
						</View>
						<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
							<Text style={styles.commonText}>{checkBeginTime.substring(0, 11)}</Text>
							<Text style={styles.commonText}>{createName||'-'}</Text>
							<Text style={styles.commonText}>{createTime.substring(0, 11)}</Text>
						</View>
					</View>:null
					}
					{this.state.tabIndex==2?
						<View style={styles.billInfoWrap}>
							<View style={{ flexDirection: 'row', alignItems: 'center' }}>
								<Text style={styles.commonTitle}>盘点日期</Text>
								<Text style={styles.commonTitle}></Text>
								<Text style={styles.commonTitle}></Text>
							</View>
							<View style={{ flexDirection: 'row', alignItems: 'flex-start',marginBottom:20*scale }}>
								<Text style={styles.commonText}>
									{checkBeginTime.substring(0, 16)}{checkEndTime?(' - '+checkEndTime.substring(0, 16)):null}
								</Text>
							</View>
							<View style={{ flexDirection: 'row', alignItems: 'center' }}>
								<Text style={styles.commonTitle}>创建人</Text>
								<Text style={styles.commonTitle}>盘点提交人</Text>
								<Text style={styles.commonTitle}>创建日期</Text>
							</View>
							<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
								<Text style={styles.commonText}>{createName||'-'}</Text>
								<Text style={styles.commonText}>{applyPersonName||'-'}</Text>
								<Text style={styles.commonText}>{createTime.substring(0, 11)}</Text>
							</View>
						</View>:null
					}
					

					<View style={styles.buttonBox}>
						<TouchableOpacity style={styles.buttonLeftPass} onPress={() => {
							this._getCheckApprove(data.item)
							}}>
								<Text style={styles.buttonLeftText}>审批流</Text>
						</TouchableOpacity>
						<View style={styles.buttonRightBox}>
							<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
								this.taskId = taskId;
								this.status = status
								this.reportId = reportId;
								this._pass();
							}}>
								<Text style={styles.buttonPassText}>通过</Text>
							</TouchableOpacity>
							<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
								this.taskId = taskId;
								this.status = status
								this.reportId = reportId;
								this._refuse();
							}}>
								<Text style={styles.buttonRefuseText}>驳回</Text>
							</TouchableOpacity>
						</View>
						
					</View>
				</View>

			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, choice, options,lightBoxData } = this.state;
		return (
			<View style={styles.container}>
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => { this.setState({ companyIndex: val }, () => { this.pageParams.pageNo = '1'; this.initPage(); 
					}) }}
						options={options}
						choice={choice} />
					: null}
				{this._renderTabWrap()}
				{
					status == 'data' ? (
						<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale, paddingLeft: 16 * scale, paddingRight: 16 * scale }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}
				<ProgressModal {...lightBoxData} />
				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 20 * scale,
	},
	filterWrap: {
		marginTop: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	dateWrap: {
		width: 110 * scale,
		height: 36 * scale,
		paddingLeft: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255 ,255 , 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		paddingRight: 14 * scale,
	},
	dateImgWrap: {
		width: 36 * scale,
		height: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255, 255, 255, .08)',
		position: 'absolute',
		top: 0,
		left: 0,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	dateText: {
		fontSize: 10 * scale,
		color: '#fff',
		opacity: .8,
		textAlign: 'center'
	},
	dateLine: {
		width: 7 * scale,
		height: 1 * scale,
		backgroundColor: 'rgba(255, 255, 255, .36)',
		marginTop: 3 * scale,
		marginBottom: 3 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: '100%',
		paddingLeft: 42 * scale,
		// paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 18 * scale,
		color: '#fff',
		fontSize: 13 * scale
	},
	searchIcon: {
		width: 22 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 12 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 10
	},
	tabItem: {
		// flex:1,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	numPoint: { backgroundColor: '#fff', width: 5, height: 5, position: 'absolute', borderRadius: 16, right: 10, top: 5 },
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		// flexDirection: 'row',
		// alignItems: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingVertical: 16 * scale,
		// justifyContent:'space-between'
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 24 * scale,
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		paddingBottom:18*scale
	},
	commonTitle: {
		flex: 1,
		color: '#708090',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
	},
	commonTitleTop:{
		flex: 1,
		fontWeight:'600',
		color: '#000',
		fontSize: 14 * scale,
		minWidth: 64 * scale,
	},
	commonTopRight:{
		fontSize: 12,
		color: '#E02020',
	},
	commonText: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#000',
		marginBottom: 10 * scale,
		fontSize: 14 * scale,
		fontWeight:'600'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 10 * scale,
	},
	buttonRightBox:{
		flexDirection: 'row',
		// alignItems: 'center',
		justifyContent: 'center',
		marginTop:5*scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	billNumWrapTop:{
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginBottom:11*scale
	},
	buttonLeftText:{
		fontSize: 12,
		color: '#0E7FFD',
	},
	buttonLeftPass:{
		paddingVertical: 10 * scale,
		paddingHorizontal:20*scale,
		marginTop:-8*scale
	}
})